package StudyCode.summary.zipfile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class AddsAnEntryAtTheRootOfTheZIP {
	public static final String ENTRY_SEPARATOR = "/";

	public static void addToZip(File fileOrDir, ZipOutputStream zos)
			throws IOException {
		addToZip(fileOrDir, null, zos);
	}

	public static void addToZip(File fileOrDir, String path,
	                            ZipOutputStream zos) throws IOException {
		if (fileOrDir.isDirectory()) {
			final String dirName = path == null ? fileOrDir.getName()
					: path + ENTRY_SEPARATOR + fileOrDir.getName();
			addDirectoryToZip(fileOrDir, dirName, zos);
		} else {
			addFileToZip(fileOrDir, path, zos);
		}
	}

	private static void addDirectoryToZip(File dir, String dirName,
	                                      ZipOutputStream zos) throws IOException {

		final ZipEntry dirEntry = new ZipEntry(dirName + ENTRY_SEPARATOR);
		zos.putNextEntry(dirEntry);
		zos.closeEntry();

		File[] children = dir.listFiles();
		if (children != null) {
			for (File file : children) {
				if (file.isDirectory()) {
					addDirectoryToZip(file, dirName + ENTRY_SEPARATOR
							+ file.getName(), zos);
				} else {
					addFileToZip(file, dirName, zos);
				}
			}
		}
	}

	private static void addFileToZip(File file, String parent,
	                                 ZipOutputStream zos) throws IOException {
		final FileInputStream is = new FileInputStream(file);
		try {
			final String entryName = parent == null ? file.getName()
					: parent + ENTRY_SEPARATOR + file.getName();
			zos.putNextEntry(new ZipEntry(entryName));

			final BufferedInputStream bis = new BufferedInputStream(is);
			try {
//				IoUtils.copyStream(bis, zos);
			} finally {
//				IoUtils.safeClose(bis);
			}

			zos.closeEntry();
		} finally {
//			IoUtils.safeClose(is);
		}
	}
}
